const uploadPathdir = 'imgs';
const defaultFileFormat = 'webp'; // 默认压缩格式
const fs = require('fs').promises;
const path = require('path');
const sharp = require("sharp");

// 根据运行环境设置文件路径
let filedir = path.join(rootDirname, 'public', uploadPathdir);
let compressedFiledir = path.join(rootDirname, 'public', 'compressed');

// 确保目录存在
(async () => {
	await fs.mkdir(filedir, {
		recursive: true
	}).catch(() => {});
	await fs.mkdir(compressedFiledir, {
		recursive: true
	}).catch(() => {});
})();

// 压缩标准
const getFileImage = async (req, res) => {
	const filename = req.params[0];
	const filepath = path.join(filedir, filename);
	const query = req.query;

	try {
		// 检查文件是否存在
		const fileExists = await fs.access(filepath, fs.constants.F_OK).then(() => true).catch(() => false);
		if (!fileExists) {
			return res.status(404).send('File not found');
		}

		// 处理GIF文件（不压缩）
		if (path.extname(filename) === '.gif') {
			return res.sendFile(filepath);
		}

		// 获取查询参数
		const {
			w,
			h,
			q
		} = query;
		const width = parseInt(w);
		const height = parseInt(h)
		const quality = parseInt(q) || 75;

		// 根据宽度或高度计算比例并设置对应的尺寸
		let resizeOptions = {};
		if (width && !height) {
			const {
				width: imgWidth,
				height: imgHeight
			} = await sharp(filepath).metadata();
			resizeOptions.height = Math.round((imgHeight / imgWidth) * query.w)
		} else if (height && !width) {
			const {
				width: imgWidth,
				height: imgHeight
			} = await sharp(filepath).metadata();
			resizeOptions.width = Math.round((imgWidth / imgHeight) * query.h)
		} else {
			resizeOptions = {
				width,
				height
			};
		}

		const outputOptions = {
			quality
		};
		
		// 构建输出文件路径
		const outputFilePath = path.join(
			compressedFiledir,
			`${path.basename(filename, path.extname(filename))}${resizeOptions.width || ''}${resizeOptions.height || ''}${quality}.${defaultFileFormat}`
		);
		// 检查压缩文件是否存在，避免重复压缩
		const compressedFileExists = await fs.access(outputFilePath, fs.constants.F_OK)
			.then(() => true)
			.catch(() => false);

		if (!compressedFileExists) {
			if (resizeOptions.width && resizeOptions.height) {
				await sharp(filepath)
					.resize(resizeOptions)
					.toFormat(defaultFileFormat, outputOptions)
					.toFile(outputFilePath);
			} else {
				await sharp(filepath)
					.toFormat(defaultFileFormat, outputOptions)
					.toFile(outputFilePath);
			}

		}

		res.sendFile(outputFilePath);
	} catch (error) {
		console.error('Error processing file:', error);
		res.status(500).send('Internal Server Error');
	}
};

module.exports = getFileImage;